package org.btik.light.meta.base.parser;

import org.btik.light.meta.base.report.DefaultReport;
import org.btik.light.meta.base.CmdCode;
import org.btik.light.meta.base.Command;
import org.btik.light.meta.base.Report;
import org.btik.light.meta.base.type.ReportParser;

import java.util.HashMap;

/**
 * @author lustre
 * @version 1.0
 * @since 2021/5/15 12:37
 * 同步命令解析
 */

public class DefaultParser implements ReportParser, CmdCode {
    @Override
    public Report parse(Command command, byte[] originalMsg) {
        HashMap<String , String> map = new HashMap<>();
        for (int i = 0; i < originalMsg.length; i++) {
            if(originalMsg[i] == ':'){
                String key = new String(originalMsg, 0 ,i);
                int vIndex = i;
                for (i++; i < originalMsg.length ; i++) {
                    if(originalMsg[i] == '\n'){
                        String val = new String(originalMsg, vIndex , i);
                        map.put(key, val);
                        break;
                    }
                }
            }
        }
        DefaultReport report = new DefaultReport();
        report.setDev(command.getTarget());
        String status = map.get(STATUS);
        if(status == null){
            report.setReturnCode(STATUS_UNKNOWN);
        }else {
            try {
                int returnCode = Integer.parseInt(status);
                report.setReturnCode(returnCode);
            }catch (Exception e){
                report.setReturnCode(STATUS_UNKNOWN);
            }
        }
        String msg = map.get(MSG);
        report.setReturnMsg(msg);
        return report;
    }
}
